

package com.maoshi.shop.mp.comment.platform.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.maoshi.shop.common.exception.MaoshiShopBindException;
import com.maoshi.shop.common.util.Json;
import com.maoshi.shop.common.util.PageParam;
import com.maoshi.shop.mp.comment.model.WeixinMaterial;
import com.maoshi.shop.mp.comment.service.WeixinMaterialService;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNewsBatchGetResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author lgh on 2019/05/14.
 */
@RestController
@RequestMapping("/weixin/material")
public class WeixinMaterialController {
	@Autowired
	private WeixinMaterialService weixinMaterialService;

	@Autowired
	private WxMpService wxMpService;

	/**
	 * 分页获取
	 */
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('weixin:material:page')")
	public ResponseEntity<IPage<WeixinMaterial>> page(PageParam<WeixinMaterial> page,WeixinMaterial weixinMaterial){
		IPage<WeixinMaterial> list = weixinMaterialService.page(page, new LambdaQueryWrapper<WeixinMaterial>()
				.eq(StrUtil.isNotBlank(weixinMaterial.getMediaType()), WeixinMaterial::getMediaType, weixinMaterial.getMediaType())
				.like(StrUtil.isNotBlank(weixinMaterial.getMediaName()), WeixinMaterial::getMediaName, weixinMaterial.getMediaName()));
		return ResponseEntity.ok(list);
	}

	/**
	 *  同步素材
	 * @throws WxErrorException
	 */
	@PostMapping("/sync/{type}")
	@PreAuthorize("@pms.hasPermission('weixin:material:sync')")
	public ResponseEntity<Void> sync(@PathVariable String type) throws WxErrorException{
		if (StrUtil.isBlank(type)) {
			throw new MaoshiShopBindException("请选择素材类型");
		}
		List<WeixinMaterial> allMaterial = new ArrayList<>();
		// 每页大小
		int pageSize = 20;
		// 一共有多少页
		int pageCount = 1;
		// 一共有多少条记录
		int totalCount = 0;
		for (int i = 0; i < pageCount; i++) {
			// 图文素材
			if (WxConsts.MaterialType.NEWS.equals(type)) {
				WxMpMaterialNewsBatchGetResult wxMpMaterialNewsBatchGetResult = wxMpService.getMaterialService().materialNewsBatchGet(i * pageSize, pageSize);
				totalCount = wxMpMaterialNewsBatchGetResult.getTotalCount();
				List<WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem> items = wxMpMaterialNewsBatchGetResult.getItems();
				for (WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem newsItem : items) {
					WeixinMaterial weixinMaterial = new WeixinMaterial();
					weixinMaterial.setCreateTime(newsItem.getUpdateTime());
					weixinMaterial.setMediaId(newsItem.getMediaId());
					WxMpMaterialNews content = newsItem.getContent();
					List<WxMpMaterialNews.WxMpMaterialNewsArticle> articles = content.getArticles();

					// 多余的文章没有实际作用，微信返回的消息只能返回一条
					WxMpMaterialNews.WxMpMaterialNewsArticle wxMpMaterialNewsArticle = articles.get(0);
					// 内容保存起来没有实际用处，清除内容
					wxMpMaterialNewsArticle.setContent(null);

					weixinMaterial.setContent(Json.toJsonString(wxMpMaterialNewsArticle));
					weixinMaterial.setMediaName(wxMpMaterialNewsArticle.getTitle());
					weixinMaterial.setCreateTime(content.getCreateTime());
					weixinMaterial.setUpdateTime(content.getUpdateTime());
					weixinMaterial.setMediaType(type);
					allMaterial.add(weixinMaterial);
				}
			}
			// 其他素材：视频，语音，图片
			else {
				WxMpMaterialFileBatchGetResult wxMpMaterialFileBatchGetResult = wxMpService.getMaterialService().materialFileBatchGet(type,i*pageSize, pageSize);
				totalCount = wxMpMaterialFileBatchGetResult.getTotalCount();
				List<WxMaterialFileBatchGetNewsItem> items = wxMpMaterialFileBatchGetResult.getItems();
				for (WxMaterialFileBatchGetNewsItem materialItem : items) {
					WeixinMaterial weixinMaterial = new WeixinMaterial();
					weixinMaterial.setCreateTime(materialItem.getUpdateTime());
					weixinMaterial.setMediaId(materialItem.getMediaId());
					weixinMaterial.setMediaName(materialItem.getName());
					weixinMaterial.setUpdateTime(materialItem.getUpdateTime());
					weixinMaterial.setMediaType(type);
					weixinMaterial.setContent(materialItem.getUrl());
					allMaterial.add(weixinMaterial);
				}
			}

			// 初始化
			if (i == 0) {
				pageCount = totalCount / pageSize;
				if (totalCount % pageSize > 0) {
					pageCount +=1 ;
				}
			}
		}
		weixinMaterialService.insertBatch(allMaterial,type);
		return ResponseEntity.ok().build();
	}

	/**
	 * 删除
	 */
	@DeleteMapping("/{mediaId}")
	@PreAuthorize("@pms.hasPermission('weixin:material:delete')")
	public ResponseEntity<Void> delete(@PathVariable String mediaId){
		weixinMaterialService.delete(mediaId);
		return ResponseEntity.ok().build();
	}

	/**
	 * 分页获取
	 */
	@GetMapping("/list")
	@PreAuthorize("@pms.hasPermission('weixin:material:info')")
	public ResponseEntity<List<WeixinMaterial>> list(){
		return ResponseEntity.ok(weixinMaterialService.list());
	}
}
